package makabakaquestionnaire.zutsoftware.framework.cloud;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class OssUtil {
    private static OSS client;
    @Autowired
    private OssConfig ossConfig;
    private void init() {
        client = new OSSClientBuilder()
                .build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    }

    //图片上传，设置http请求为image/jpg
    public String upload(InputStream inputStream, String path){
        this.init();
        try {
            //上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), path, inputStream);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("image/jpg");
            putObjectRequest.setMetadata(metadata);
            PutObjectResult result = client.putObject(putObjectRequest);
            client.setBucketAcl(ossConfig.getBucketName(), CannedAccessControlList.PublicRead);
            if (result!=null){
                System.out.println("=========>OSS文件上传成功，OSS地址：" + ossConfig.getDomain() + "/" + path);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ossConfig.getDomain() + "/" + path;
    }
    /**
     * 查询路径下的所有文件
     */
    public List<String> getObjectList(){
        List<String> res=new ArrayList<>();
        this.init();
        System.out.println("=========>查询文件列表");
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucketName());
        //列出bucketName的目录下所有的文件
        listObjectsRequest.setPrefix("wj/");
        ObjectListing list = client.listObjects(listObjectsRequest);
        for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
            res.add(objectSummary.toString());
        }
        return res;
    }


}
